package com.study.bookstore.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.study.bookstore.domain.Author;
import com.study.bookstore.domain.BookBasic;
import com.study.bookstore.domain.BookType;
import com.study.bookstore.service.BookBasicService;
import com.study.bookstore.web.rest.errors.BadRequestAlertException;
import com.study.bookstore.web.rest.util.HeaderUtil;
import com.study.bookstore.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing BookBasic.
 */
@RestController
@RequestMapping("/api")
public class BookBasicResource {

    private final Logger log = LoggerFactory.getLogger(BookBasicResource.class);

    private static final String ENTITY_NAME = "bookBasic";

    private final BookBasicService bookBasicService;

    public BookBasicResource(BookBasicService bookBasicService) {
        this.bookBasicService = bookBasicService;
    }

    /**
     * POST  /book-basics : Create a new bookBasic.
     *
     * @param bookBasic the bookBasic to create
     * @return the ResponseEntity with status 201 (Created) and with body the new bookBasic, or with status 400 (Bad Request) if the bookBasic has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/book-basics")
    @Timed
    public ResponseEntity<BookBasic> createBookBasic(@RequestBody BookBasic bookBasic) throws URISyntaxException {
        log.debug("REST request to save BookBasic : {}", bookBasic);
        if (bookBasic.getId() != null) {
            throw new BadRequestAlertException("A new bookBasic cannot already have an ID", ENTITY_NAME, "idexists");
        }
        BookBasic result = bookBasicService.save(bookBasic);
        return ResponseEntity.created(new URI("/api/book-basics/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /book-basics : Updates an existing bookBasic.
     *
     * @param bookBasic the bookBasic to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated bookBasic,
     * or with status 400 (Bad Request) if the bookBasic is not valid,
     * or with status 500 (Internal Server Error) if the bookBasic couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/book-basics")
    @Timed
    public ResponseEntity<BookBasic> updateBookBasic(@RequestBody BookBasic bookBasic) throws URISyntaxException {
        log.debug("REST request to update BookBasic : {}", bookBasic);
        if (bookBasic.getId() == null) {
            return createBookBasic(bookBasic);
        }
        BookBasic result = bookBasicService.save(bookBasic);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, bookBasic.getId().toString()))
            .body(result);
    }

    /**
     * GET  /book-basics : get all the bookBasics.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of bookBasics in body
     */
    @GetMapping("/book-basics")
    @Timed
    public ResponseEntity<List<BookBasic>> getAllBookBasics(Pageable pageable) {
        log.debug("REST request to get a page of BookBasics");
        Page<BookBasic> page = bookBasicService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/book-basics");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /book-basics/:id : get the "id" bookBasic.
     *
     * @param id the id of the bookBasic to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the bookBasic, or with status 404 (Not Found)
     */
    @GetMapping("/book-basics/{id}")
    @Timed
    public ResponseEntity<BookBasic> getBookBasic(@PathVariable Long id) {
        log.debug("REST request to get BookBasic : {}", id);
        BookBasic bookBasic = bookBasicService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(bookBasic));
    }

    /**
     * DELETE  /book-basics/:id : delete the "id" bookBasic.
     *
     * @param id the id of the bookBasic to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/book-basics/{id}")
    @Timed
    public ResponseEntity<Void> deleteBookBasic(@PathVariable Long id) {
        log.debug("REST request to delete BookBasic : {}", id);
        bookBasicService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
    @GetMapping("/book-basics/keyword")
    @Timed
    public ResponseEntity getBookBasicByLike(@RequestParam("type")Integer type,@RequestParam("keyword") String keyword,@ApiParam Pageable pageable){
        try {
            Page<BookBasic> page=bookBasicService.findBookBasicLike(type,keyword, pageable);
            HttpHeaders headers=PaginationUtil.generatePaginationHttpHeaders(page,"/api/book-basics");
            return new ResponseEntity<>(page,headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e);
        }
    }

    @GetMapping("/book-basics/bookType")
    @Timed
    public ResponseEntity findBookBasicByBookTypeId(@RequestParam("bookType") BookType type, @ApiParam Pageable pageable){
        try {
            Page<BookBasic> page = bookBasicService.findBookBasicByBookTypeId(type,pageable);
            HttpHeaders headers=PaginationUtil.generatePaginationHttpHeaders(page,"/book-basics");
            return new ResponseEntity<>(page,headers,HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e);
        }
    }

    @GetMapping("/book-basics/authorId")
    @ApiOperation(value = "根据作者id获取其它作品")
    @Timed
    public ResponseEntity findBookBasicsByAuthodId(@RequestParam("authorId") Author author, @ApiParam Pageable pageable){
        try {
            Page<BookBasic> page=bookBasicService.findBookBasicsByAuthodId(author, pageable);
            HttpHeaders headers=PaginationUtil.generatePaginationHttpHeaders(page,"/book-basics");
            return new ResponseEntity<>(page,headers,HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e);
        }
    }
}
